const { join } = require("path");
const { existsSync } = require("fs");
const { spawn } = require("child_process");
const fs = require('fs').promises;  
const path = require("path");

let frpcProcess = null;
let logs = "";
let logCallback = null;
let frpcRunning = false;


function pushLog(msg) {
  logs += msg;
  if (logCallback) logCallback(msg);
}

async function startFrpc(config, onLog) {
  if (frpcProcess) throw new Error("frpc 已在运行");
  frpcRunning = true;
  logCallback = onLog; // 设置日志推送回调

  const exePath = join(config.frp_path, "frpc.exe");
  const tomlPath = join(config.frp_path, "frpc.toml");
  if (!existsSync(exePath)) throw new Error("frpc.exe 不存在");
  if (!existsSync(tomlPath)) throw new Error("frpc.toml 不存在");

  frpcProcess = spawn(exePath, ["-c", tomlPath], {
    cwd: config.frp_path,
    windowsHide: true,
  });

  pushLog(`\n[frpc 启动于 ${new Date().toLocaleString()}]\n`);

  frpcProcess.stdout.on("data", (data) => {
    pushLog(data.toString());
    console.log("[frpc stdout]", data.toString());
  });
  frpcProcess.stderr.on("data", (data) => pushLog(data.toString()));
  frpcProcess.on("close", (code) => {
    pushLog(`\nfrpc 退出，退出码：${code}\n`);
    frpcProcess = null;
    frpcRunning = false;
  });
  frpcProcess.on("error", (err) => {
    pushLog(`[错误] ${err.message}\n`);
  });
}

function stopFrpc() {
  if (frpcProcess) {
    frpcProcess.kill();
    frpcRunning = false;
    return true;
  } else {
    throw new Error("frpc 未在运行");
  }
}

function getFrpcLogs() {
  return logs || "暂无日志";
}

function getStatus() {
  return { running: frpcRunning };
}

async function getVersion() {
  /**根据开发环境和生产环境判断版本目录 */
  const LOCAL_VERSIONS_DIR = path.join(__dirname, "../public", "versions");
  // 获取 app 实例（兼容主进程和渲染进程）
  console.log(__dirname, LOCAL_VERSIONS_DIR)
  try {
    // 读取目录内容
    const entries = await fs.readdir(LOCAL_VERSIONS_DIR, { withFileTypes: true });
    
    // 过滤并处理文件夹
    const versions = await Promise.all(
      entries
        .filter(entry => entry.isDirectory()) // 只处理文件夹
        .filter(entry => /^frp_[\d.]+_windows_\w+$/.test(entry.name)) // 验证文件夹名格式
        .map(async (entry) => {
          const folderName = entry.name;
          const folderPath = path.join(LOCAL_VERSIONS_DIR, folderName);
          
          // 获取文件夹信息（使用statfs可能更合适，但这里用stat获取创建时间）
          const stats = await fs.stat(folderPath);
          
          // 提取版本号
          const versionMatch = folderName.match(/frp_([\d.]+)_windows_\w+/);
          const version = versionMatch ? 'v' + versionMatch[1] : "未知版本";
          
          // 提取架构信息
          const archMatch = folderName.match(/frp_[\d.]+_windows_(\w+)/);
          const arch = archMatch ? archMatch[1] : "未知架构";
          
          return {
            name: folderName,
            version,
            arch,
            size: "N/A", // 文件夹没有明确大小，可改为计算文件夹内所有文件大小总和
            timestamp: stats.mtime,
            path: `${LOCAL_VERSIONS_DIR}\\${folderName}`, // 静态资源路径
          };
        })
    );
    
    return versions.sort((a, b) => b.timestamp - a.timestamp);
    
  } catch (error) {
    console.error("获取版本列表失败:", error);
    throw new Error("无法获取本地版本列表");
  }
}
// 格式化文件大小
function formatSize(bytes) {
  if (bytes === 0) return "0 Bytes";
  const k = 1024;
  const sizes = ["Bytes", "KB", "MB", "GB"];
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + " " + sizes[i];
}


module.exports = {
  startFrpc,
  stopFrpc,
  getFrpcLogs,
  getStatus,
  getVersion,
};
